#include <stdio.h>
#include "LogicPool/LogicQDC.h"


void LogicQDC::Init()
{
#if (LOGIC_QDC_VERSION == 10)
  SetStartDelay(17);
  SetStopDelay(17+20);
#else
  SetStartDelay(17);
  SetStopDelay(17);
  SetGateTime(30);
#endif
}


void LogicQDC::SetMode(int mode)
{
  // mode
  //  0 : data is adc(stop) - adc(start)  [default]
  //  1 : adc[start]
  //  2 : adc[stop]
  //  3 : adc[start] and adc[stop]
  this->mode = mode;
#if (LOGIC_QDC_VERSION == 10)
  SetAddress(2);
  logicpool.WriteWord((mode & 0x03) << 14);
#else
  SetAddress(2);
  //printf("\nSetMode: 0x%x\n", ((mode & 0x03) << 14) | startDelay);
  logicpool.WriteWord(((mode & 0x03) << 14) | startDelay);
#endif
}


int LogicQDC::GetNEvents()
{
  uint16_t n;

  SetAddress(4);
  n = logicpool.ReadWord();
  // bits [0..10] contain the number of events
#if (LOGIC_QDC_VERSION == 10)
  return n & 0x07ff;
#elif LOGIC_QDC_VERSION == 20
  return n & 0x3fff;
#else
  return n & 0x7fff;
#endif
}


bool LogicQDC::Overflow()
{
  uint16_t n;

  SetAddress(4);
  n = logicpool.ReadWord();
  // bit [14] contains the overflow bit
#if (LOGIC_QDC_VERSION == 10)
  return (n & 0x4000) > 0;
#else
  return (n & 0x8000) > 0;
#endif
}


void LogicQDC::ReadEvents(int16_t * data, uint16_t n)
{
  SetAddress(2);
  if (n > 1)
    logicpool.ReadWordFIFO((uint16_t *)data, n);
  else
    *data = logicpool.ReadWord();
}


void LogicQDC::SetStartDelay(uint8_t delay)
{
  startDelay = delay;
#if (LOGIC_QDC_VERSION == 10)
  SetAddress(1);
  logicpool.WriteByte(delay);
#else
  SetAddress(2);
  //printf("\nSetStartDelay: 0x%x\n", ((mode & 0x03) << 14) | startDelay);
  logicpool.WriteWord(((mode & 0x03) << 14) | startDelay);
#endif
}


void LogicQDC::SetStopDelay(uint8_t delay)
{
  stopDelay = delay;
  SetAddress(4);
  logicpool.WriteByte(delay);
}


void LogicQDC::Clear()
{
    SetStopDelay(stopDelay);
}


#if (LOGIC_QDC_VERSION >= 20)
void LogicQDC::SetGateTime(uint16_t delay)
{
    gateTime = delay;
    SetAddress(1);
    logicpool.WriteByte(delay);
}
#endif
